<?php

namespace IDock\Insurance\ZMBX;

use IDock\Common\BaseInterface\BuilderInterface;
use IDock\Http\Request;
use IDock\Http\Response;
use IDock\Insurance\ZMBX\Request\AllZMBXRequest;
use IDock\Insurance\ZMBX\Request\PolicyPaymentRequest;
use IDock\Insurance\ZMBX\Request\RSAPublicKeyRequest;
use IDock\Insurance\ZMBX\Response\AllDBICResponse;
use IDock\Insurance\ZMBX\Response\AllZMBXResponse;

class Builder implements BuilderInterface
{

    public function getConfig(): array
    {
        return $this->config;
    }

    protected $config;
    protected $secret;
    protected $proxy;
    protected $callbackUrl;
    protected $passMsgUrl;

    public function execute(Request $request): Response
    {
        /*** @var AllZMBXRequest $request */
        $request->loadConfig($this->config);
        $request->setRequestId(md5(uniqid()));
        if(property_exists($request,'callbackUrl')){
            $request->callbackUrl = $this->callbackUrl;
            $request->passMsgUrl = $this->passMsgUrl;
        }
        $data = $request->generate();
        $param = [
            'head' => [
                'transCode' => $request->requestCode,
                'transType' => 'Req',
                'token' => $request->token,
                'source' => $request->source,
            ]
        ];

        $param = array_merge($data,$param);
        $request->setPreParameter($param);
        $this->sign($request);
        return $this->request($request);
    }

    public function generate(Request $request): array
    {
        return $request->generate();
    }


    public function sign(Request $request): Request
    {
        $data = $request->getPreParameter();
        $signature = openssl_encrypt(json_encode($data,320), 'AES-128-ECB', $this->secret, OPENSSL_RAW_DATA);
        $sign = bin2hex($signature);
        $request->setBizParam($sign);
        return $request;
    }

    public function exceptionResponse($request, $errorMessage): Response
    {
        $response = $request->getResponse();

        $response = new $response;
        $response->setCode('500');
        $response->setError($errorMessage);

        return $response;
    }

    public function request(Request $request): Response
    {
        /*** @var AllZMBXResponse $response */
        $response = $request->request($request);
        $response->setVisitor($request->getVisitor());

        $response->decrypt($this->secret, $request);
        $response->resolve();
        if ($response->isSuccess()) {
            $response->printerInit();
        }
        return $response;
    }

    /**
     * 数据加密
     * @param Request $request
     */
    public function encrypt(Request $request)
    {

    }

    /**
     * 加密去空格
     * @param string $str
     * @return array|string|string[]
     * @version 4.0
     */
    private static function replace(string $str)
    {
        return str_replace(["\r\n", "\n", "\t", "\r",' '], ['', '', '', '', ''], $str);
    }
}
